import Vue from "vue";
import Router from "vue-router";
import login from "@/views/login/index.vue";
import home from "@/views/home/index.vue";
import testCase from "@/views/replan/Index.vue";

import store from "@/store";

// 1.注册路由插件
Vue.use(Router);

// 懒加载组件，代码使用了动态导入（() => import("@/views/Home.vue")），这样Home组件会在访问/时按需加载，而不是打包进入JS文件，优化性能。
// const home = () => import("@/views/home/index.vue");

const router = new Router({
  mode: "history", //使用history模式
  // base: process.env.BASE_URL, // 设置路由的基础路径(Base URL)，即所有路由的前缀
  // mode: "hash",
  base: "/",
  routes: [
    {
      path: "/",
      name: "Home",
      component: home, // 指当前路由(如path: "/") 对应的组件(这里是Home组件)，当用户访问该路径时，Vue Router 会渲染Home 组件
      meta: {
        title: "首页", // 用于浏览器标题
        requiresAuth: true, //是否需要登录权限
      },
    },
    {
      path: "/login",
      name: "Login",
      component: login,
      meta: { title: "登陆" },
    },
    {
      path: "/replan",
      name: "Replan",
      component: testCase,
      meta: { title: "测试用例" },
    },
  ],
});

router.beforeEach((to, from, next) => {
  const token = store.state.token || localStorage.getItem("token");
  console.log("token from store:", store.state.token);
  console.log("token from localStorage:", localStorage.getItem("token"));
  if (to.meta.requiresAuth && !token) {
    // 如果访问需要登录的页面但没登录
    next({ path: "/login" });
  } else if (to.path === "/login" && token) {
    // 已登录还访问登录页，直接跳转首页
    next({ path: "/" });
  } else {
    next(); // 正常放行
  }
});
export default router;
